package com.lb.myeam.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lb.myeam.core.dao.TeamDao;
import com.lb.myeam.core.dao.impl.TeamDaoImpl;
import com.lb.myeam.core.entity.TeamEntity;

public class TeamServlet extends HttpServlet {

	private TeamDao teamDao = new TeamDaoImpl();

	// doGet
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	// doPost
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("post====");
		String act = request.getParameter("act");
		System.out.println(act);
		if ("add".equals(act)) {
			doAdd(request, response);
		}else if ("query".equals(act)) {
			doQuery(request, response);
		}else if ("delete".equals(act)) {
			doDelete(request, response);
		}else if ("update".equals(act)) {
			doUpdate(request, response);
		}
	}

	// doAdd
	public void doAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String teamName = request.getParameter("teamName");
		teamDao.add(new TeamEntity(teamName, "-1"));
		doQuery(request, response);
	}

	// doQuery
	public void doQuery(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doQuery");
		List<TeamEntity> teamList = teamDao.query();
		System.out.println(teamList);
		req.setAttribute("teamList", teamList);
		req.getRequestDispatcher("../pages/team/team_list.jsp").forward(
				req, resp);
	}

	// doDelete
	public void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("go to servlet doDelete");
		teamDao.delete(req.getParameter("id"));
		doQuery(req, resp);
		
	}
	
	// doUpdate
		public void doUpdate(HttpServletRequest req, HttpServletResponse resp)
				throws ServletException, IOException {
			System.out.println("go to servlet doUpdate");
			String id=req.getParameter("id");
			String name=req.getParameter("teamName");
			Date time=new Date();
			String pid=req.getParameter("pid");
			System.out.println(id+","+name+","+time+","+pid);
			TeamEntity team= new TeamEntity(id,name,time,pid);
			teamDao.update(team);
			req.getRequestDispatcher("../pages/team/team_update.jsp").forward(
					req, resp);
			
		}
}
